package com.glela.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.glela.api.upload.qiniu.general.QiniuUtils;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.Base64Util;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.MD5;
import com.glela.common.util.StringUtils;
import com.glela.goods.mapper.*;
import com.glela.goods.model.*;
import com.glela.goods.model.request.RequestGYBaseModel;
import com.glela.goods.model.vo.*;
import com.glela.goods.service.ReceiveGoodsService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.util.DateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Service("receiveGoodsService")
@Scope("singleton")
public class ReceiveGoodsServiceImpl implements ReceiveGoodsService {
    private final String[] roleIds = {"3","4","5","6","7","8","9","10","11"};

    private static Logger logger = LoggerFactory.getLogger(ReceiveGoodsServiceImpl.class);
    @Value("${channel.appSecret}")
    private String appSecret;
    @Autowired
    private ReceiveGoodsCacheMapper receiveGoodsCacheMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsNavigateMapper goodsNavigateMapper;
    @Autowired
    private GoodsDetailMapper goodsDetailMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private BaseRestrictionsService baseRestrictionsService;
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private GoodsSpecificationImagesMapper goodsSpecificationImagesMapper;
    @Autowired
    private GoodsCommissionMapper goodsCommissionMapper;
    @Autowired
    private SpecificationMapper specificationMapper;
    @Autowired
    private SpecificationDetailMapper specificationDetailMapper;


    /**
     * @Description: 接收商品写入缓存表
     * @Author: zhangrenjie
     * @Date: 2018/1/31 21:08
     *
     */
    @Override
    public ResponseEntity<?> receiveGoodsData(RequestGYBaseModel model) {
        // 验签
        String sign= MD5.passmd5(model.getData()+ appSecret).toUpperCase();
        if (!sign.equals(model.getSign())) {
            logger.error("签名验证失败！解密签名结果："+sign+"!="+model.getSign());
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C70000), HttpStatus.OK);
        }
        // 解开业务参数
        String data = Base64Util.decode(model.getData());
        if (StringUtils.isEmpty(data)) {
            logger.error("缺少商品信息参数：data数据为空");
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C70001), HttpStatus.OK);
        }
        List<GoodsSendVo> goodsSendVoList = null;
        try {
            goodsSendVoList = JSON.parseObject(data,new TypeReference<List<GoodsSendVo>>(){});
        } catch (Exception e ) {
            logger.error("JSON解析异常data： "+data);
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C70002), HttpStatus.OK);
        }
        if (CollectionUtils.isEmpty(goodsSendVoList)) {
            logger.error("解析错误商品信息参数：data： "+data);
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C70001), HttpStatus.OK);
        }
        for (GoodsSendVo goodsSendVo : goodsSendVoList) {//默认只有一个
            //维护商品缓存表
            String sendUpdateGoods = goodsSendVo.getSendUpdateGoods();
            String sendUpdateGoodsDetail = goodsSendVo.getSendUpdateGoodsDetail();
            String sendUpdateSalePrice = goodsSendVo.getSendUpdateSalePrice();
            //根据类型判断是新增操作还是更新操作
            if (!"1".equals(sendUpdateGoods) && !"1".equals(sendUpdateGoodsDetail) && !"1".equals(sendUpdateSalePrice)) {
                //add操作先查询是否已经存在（不允许多次add操作）
                ReceiveGoodsCache bean = new ReceiveGoodsCache();
                bean.setType("add");
                bean.setGoodsCode(goodsSendVo.getGoodsCode());
                List<ReceiveGoodsCache> selectAll = receiveGoodsCacheMapper.selectAll(bean);
                if (!CollectionUtils.isEmpty(selectAll)) {
                    logger.error("同一商品不允许多次新增操作！商品编码："+goodsSendVo.getGoodsCode());
                    return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C70003), HttpStatus.OK);
                }
                ReceiveGoodsCache receiveGoodsCache = new ReceiveGoodsCache();
                receiveGoodsCache.setGoodsCode(goodsSendVo.getGoodsCode());
                receiveGoodsCache.setData(data);
                receiveGoodsCache.setType(CommonConstants.ADD);
                receiveGoodsCache.setStatus(new Byte("0"));//未同步
                receiveGoodsCache.setCreatTime(new Date());
                receiveGoodsCacheMapper.insertSelective(receiveGoodsCache);
            }else{
                //update操作---必须已经有商品存在，否则不允许直接跟新操作
                ReceiveGoodsCache bean = new ReceiveGoodsCache();
                bean.setType("add");
                bean.setGoodsCode(goodsSendVo.getGoodsCode());
                List<ReceiveGoodsCache> selectAll = receiveGoodsCacheMapper.selectAll(bean);
                if (CollectionUtils.isEmpty(selectAll)) {
                    logger.error("商品未推送，不允许进行更新操作！商品编码："+goodsSendVo.getGoodsCode());
                    return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C70004), HttpStatus.OK);
                }
                ReceiveGoodsCache receiveGoodsCache = new ReceiveGoodsCache();
                receiveGoodsCache.setGoodsCode(goodsSendVo.getGoodsCode());
                receiveGoodsCache.setData(data);
                receiveGoodsCache.setType(CommonConstants.UPDATE);
                receiveGoodsCache.setStatus(new Byte("0"));//未同步
                receiveGoodsCache.setCreatTime(new Date());
                receiveGoodsCacheMapper.insertSelective(receiveGoodsCache);
                logger.info("商品："+goodsSendVo.getGoodsCode()+"于"+
                        DateUtils.getNowString(DateUtils.DATE_TIME_FORMAT)+"进行了更新操作!");
            }
        }
        return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
    }

    @Override
    public List<ReceiveGoodsCache> selectAllReceiveGoodsCache(ReceiveGoodsCache bean) {
        return receiveGoodsCacheMapper.selectAll(bean);
    }

    /*@Override
    public ResponseEntity<?> sysGoodsDataToStore() throws InterruptedException {
       *//* //查询缓存表根据类型开始初始化商品信息
        ReceiveGoodsCache bean = new ReceiveGoodsCache();
        bean.setStatus(new Byte("0"));//未同步
        List<ReceiveGoodsCache> cacheList = receiveGoodsCacheMapper.selectAll(bean);
        List<GoodsSendVo> goodsSendVoList = null;
        if (!CollectionUtils.isEmpty(cacheList)) {
            for (ReceiveGoodsCache receiveGoodsCache : cacheList) {
                try {
                    goodsSendVoList = JSON.parseObject(receiveGoodsCache.getData(),new TypeReference<List<GoodsSendVo>>(){});
                } catch (Exception e ) {
                    logger.error("商品："+receiveGoodsCache.getGoodsCode()+"JSON解析异常！原因："+e.getMessage());
                    e.printStackTrace();
                }
                if (goodsSendVoList != null && !goodsSendVoList.isEmpty()) {
                    try {
                        this.initGoods(goodsSendVoList,receiveGoodsCache.getType());
                    } catch (Exception e) {
                        logger.error("商品："+receiveGoodsCache.getGoodsCode()+"初始化失败!原因："+e.getMessage());
                        e.printStackTrace();
                        continue;//发生异常直接跳过
                    }
                    //更新缓存表状态
                    ReceiveGoodsCache receiveGood = new ReceiveGoodsCache();
                    receiveGood.setId(receiveGoodsCache.getId());
                    receiveGood.setStatus(new Byte("1"));
                    receiveGoodsCacheMapper.updateByPrimaryKeySelective(receiveGood);
                    Thread.sleep(500);
                }
            }
        }
        return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);*//*
    }*/
    /**
     * @Description: 初始化商品相关信息（包括新增和更新操作）
     * @Author: zhangrenjie
     * @Date: 2018/1/31 21:51
     *
     */
    @Override
    @Transactional
    public void addInitGoods(List<GoodsSendVo> goodsSendVoList,String type) throws RuntimeException {
        //根据类型区分新增和更新
        for (GoodsSendVo goodsSendVo : goodsSendVoList) {//一次最多十个商品
            List<GoodsNavigate> goodsNavigateList = goodsSendVo.getGoodsNavigateList();//轮播图
            List<GoodsDetail> goodsDetailList = goodsSendVo.getGoodsDetailList();//详情
            List<ProductSendVo> products = goodsSendVo.getProducts();//规格和库存

            if (CommonConstants.ADD.equals(type)) {
                //新增商品信息-先检查是否已经存在
                List<Goods> goods1 = goodsMapper.selectGoodsByBN(goodsSendVo.getGoodsCode());
                if (!CollectionUtils.isEmpty(goods1)) {
                    throw new RuntimeException("新增失败！商品："+goodsSendVo.getGoodsCode()+"已存在不允许重复添加");
                }
                GoodsNew goods = null;
                goods = changeGoods(goodsSendVo);
                goodsMapper.insertSelective(goods);
                //获取商品主键（商品ID）
                Goods g = goodsMapper.selectGoodsByBN(goodsSendVo.getGoodsCode()).get(0);
                //初始化商品佣金
                List<String> asList = Arrays.asList(roleIds);//全部角色
                List<GoodsCommission> commissionList = new ArrayList<>();
                for (String s : asList) {
                    GoodsCommission commission = new GoodsCommission();
                    commission.setGoodId(g.getId());
                    commission.setRoleId(Integer.parseInt(s));
                    commission.setCommissionType(1);
                    commission.setCommission(5);//默认5%
                    commissionList.add(commission);
                }
                //初始化商品佣金
                if (!CollectionUtils.isEmpty(commissionList)) {
                    goodsCommissionMapper.insertSelectiveBatch(commissionList);
                }
                //商品轮播图
                if (!CollectionUtils.isEmpty(goodsNavigateList)) {
                    for (GoodsNavigate goodsNavigate : goodsNavigateList) {
                        goodsNavigate.setGoodId(g.getId());
                        goodsNavigate.setNavigateImage(uploadQN(goodsNavigate.getNavigateImage()));
                    }
                    goodsNavigateMapper.insertSelectiveBatch(goodsNavigateList);
                }
                //商品详情
                if (!CollectionUtils.isEmpty(goodsDetailList)) {
                    for (GoodsDetail goodsDetail : goodsDetailList) {
                        goodsDetail.setGoodId(g.getId());
                        goodsDetail.setImagePath(uploadQN(goodsDetail.getImagePath()));
                    }
                    goodsDetailMapper.insertSelectiveBatch(goodsDetailList);
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //商品规格和库存
                if (!CollectionUtils.isEmpty(products)) {
                    List<Product>   productsNew  = new ArrayList<Product> ();
                    List<GoodsSpecificationImages>   productsImg  = new ArrayList<GoodsSpecificationImages> ();
                    List<Inventory> InventorysNewList  = new ArrayList<Inventory> ();
                    for (ProductSendVo product : products) {
                        //转换规格
                        Product p = null ;
                        p = changeProduct(product,g.getId());
                        productsNew.add(p);
                        //转换规格图片（一个货品可以对应多个规格小图）
                        List<GoodsSpecificationImages> imgs = null;
                        imgs = changeProductImg(product,g.getId());
                        productsImg.addAll(imgs);
                    }
                    //先进行规格写入操作
                    if (!CollectionUtils.isEmpty(productsNew)) {
                        productMapper.insertSelectiveBatch(productsNew);
                    }
                    //规格图片写入操作
                    if (!CollectionUtils.isEmpty(productsImg)) {
                        //过滤重复的问题----set集合配合 重写hashCode、equals
                        Set result = new HashSet(productsImg);
                        productsImg = new ArrayList<>(result);
                        goodsSpecificationImagesMapper.insertSelectiveBatch(productsImg);
                    }
                    //库存
                    for (ProductSendVo product : products) {
                        //库存转换
                        Inventory i = null;
//                        i = changeInVentry(product.getInventory(),g.getId(),product.getProductBn());
                        //改为productId
                        i = changeInVentry(product.getInventory(),g.getId(),String.valueOf(product.getId()));
                        if (i != null) {
                            InventorysNewList.add(i);
                        }
                    }
                    //批量插入
                    if (!CollectionUtils.isEmpty(InventorysNewList)) {
                        inventoryMapper.insertSelectiveBatch(InventorysNewList);
                    }
                }
            } else if (CommonConstants.UPDATE.equals(type)) {//更新操作
                //更新商品信息
                List<Goods> goods1 = goodsMapper.selectGoodsByBN(goodsSendVo.getGoodsCode());
                if (CollectionUtils.isEmpty(goods1)) {
                    throw new RuntimeException("更新商品基础信息失败！商品："+goodsSendVo.getGoodsCode()+"不存在");
                }
                long goodId = goods1.get(0).getId();
                if (goodsSendVo.getSendUpdateGoods()!=null&&goodsSendVo.getSendUpdateGoods().equals("1")) {//更新商品信息
                    GoodsNew goods = null;
                    goods = changeGoods(goodsSendVo);
                    goods.setId(goodId);//使用主键更新
                    goodsMapper.updateGoodsByPrimaryKeySelective(goods);
                }
                if (goodsSendVo.getSendUpdateGoodsDetail()!=null && goodsSendVo.getSendUpdateGoodsDetail().equals("1")) {//更新详情和轮播图
                    //更新商品轮播图
                    if (!CollectionUtils.isEmpty(goodsNavigateList)) {
                        //先删除旧轮播图，在插入新的
                        goodsNavigateMapper.deleteByGoodId(goodId);
                        for (GoodsNavigate goodsNavigate : goodsNavigateList) {
                            goodsNavigate.setGoodId(goodId);
                            goodsNavigate.setNavigateImage(uploadQN(goodsNavigate.getNavigateImage()));
                        }
                        goodsNavigateMapper.insertSelectiveBatch(goodsNavigateList);
                    }
                    //更新商品详情
                    if (!CollectionUtils.isEmpty(goodsDetailList)) {
                        goodsDetailMapper.deleteByGoodId(goodId);
                        for (GoodsDetail goodsDetail : goodsDetailList) {
                            goodsDetail.setGoodId(goodId);
                            goodsDetail.setImagePath(uploadQN(goodsDetail.getImagePath()));
                        }
                        goodsDetailMapper.insertSelectiveBatch(goodsDetailList);
                    }
                }
                if (goodsSendVo.getSendUpdateSalePrice()!=null&&goodsSendVo.getSendUpdateSalePrice().equals("1")) {//更新价格
                    if (!CollectionUtils.isEmpty(products)) {
                        //解析新的库存（更新价格）
                        for (ProductSendVo product : products) {
//                            //根据Goodid和规格编码去查找规格id（主键）
//                            String productBn = product.getProductBn().replaceAll("-", "");
//                            Product pro = productMapper.selectProductByGoodIdAndProductBn(goodId,productBn);
//                            if (null == pro) {
//                                throw new RuntimeException("更新规格价格失败！商品："+goodsSendVo.getGoodsCode()+"下规格:"+productBn+"信息不存在");
//                            }
                            //根据Goodid和外部编码去查找我们自己的规格id
                            Product pro = productMapper.selectProductByGoodIdAndExtendCode(goodId,product.getId());
                            if (null == pro) {
                                throw new RuntimeException("更新规格价格失败！商品："+goodsSendVo.getGoodsCode()+"下外部规格为:"+product.getId()+"信息不存在");
                            }
                            //根据规格ID去查找库存
                            Inventory inventory = inventoryMapper.selectInventoryByPid(pro.getId());
                            if (null == inventory) {
                                throw new RuntimeException("更新规格价格失败！商品："+goodsSendVo.getGoodsCode()+"下外部规格为:"+product.getId()+"的库存信息不存在");
                            }
                            //根据库存主键更新价格(只更新价格)
                            inventory.setSalePrice(product.getInventory().getSalePrice());
                            inventory.setSettlementPrice(product.getInventory().getSettlementPrice());
                            inventoryMapper.updateByPrimaryKeySelective(inventory);
                        }
                    }
                }
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * @Description: 数据更新（仅仅为了修改原始异常数据）
     * @Author: zhangrenjie
     * @Date: 2018/3/1 15:19
     *
     */
    /*@Override
    @Transactional
    public void addInitGoods(List<GoodsSendVo> goodsSendVoList,String type) throws RuntimeException {
        //根据类型区分新增和更新
        int i = 0;
        for (GoodsSendVo goodsSendVo : goodsSendVoList) {
            if (i > 20) {//每次处理20个
                return;
            }
            List<GoodsNavigate> goodsNavigateList = goodsSendVo.getGoodsNavigateList();//轮播图
            List<GoodsDetail> goodsDetailList = goodsSendVo.getGoodsDetailList();//详情
            List<ProductSendVo> products = goodsSendVo.getProducts();//规格和库存

            if (CommonConstants.ADD.equals(type)) {

            } else if (CommonConstants.UPDATE.equals(type)) {//更新操作
                //更新商品信息
                List<Goods> goods1 = goodsMapper.selectGoodsByBN(goodsSendVo.getGoodsCode());
                if (CollectionUtils.isEmpty(goods1)) {
                    throw new RuntimeException("更新商品基础信息失败！商品："+goodsSendVo.getGoodsCode()+"不存在");
                }
                long goodId = goods1.get(0).getId();
                GoodsNew goods = null;
                goods = changeGoodsNew(goodsSendVo);
                goods.setId(goodId);//使用主键更新
                goodsMapper.updateGoodsByPrimaryKeySelective(goods);
                //更新product的json字符串
                for (ProductSendVo product : products) {
                    //先查询规格是否存在
                    Product pro = productMapper.selectProductByGoodIdAndExtendCode(goodId, product.getId());
//                    if (null == pro) {
//                        throw new RuntimeException("更新商品规格失败！商品："+goodsSendVo.getGoodsCode()+"的外部编码："+product.getId()+"对应的规格不存在");
//                    }
                    if (null != pro) {
                        //转换规格
                        Product p = changeProduct(product,goodId);
                        p.setId(pro.getId());
                        //主键更新规格
                        productMapper.updateByPrimaryKeySelective(p);
                    }
                }
            }
            i++;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }*/
    /**
     * @Description: 根据货品转换为货品的规格小图对象
     * @Author: zhangrenjie
     * @Date: 2018/2/2 16:10
     *
     */
    private List<GoodsSpecificationImages> changeProductImg(ProductSendVo product, long goodId) {
        List<GoodsSpecificationImages> imgList =null;
        String specInfo = product.getSpecInfo();
        String imagePath = product.getImagePath();
        if (!StringUtils.isEmpty(specInfo) && !StringUtils.isEmpty(imagePath)) {
            imgList = new ArrayList<>();
            String[] split = specInfo.split(",");//第一次：9963,9911；第二次9963,9912  等......
            for (String s : split) {
                boolean flag = true;
//                if (!imgList.isEmpty()) {//校验是有重复的SpecificationDetailId值
//                    for (GoodsSpecificationImages g : imgList) {
//                        if (g.getSpecificationDetailId().equals(s)) {//相等说明已经存在该规格图片了
//                            flag = false;//说明已经存在过该规格图片了
//                            break;//中断内循环
//                        }
//                    }
//                }
                if (flag) {
                    GoodsSpecificationImages g = new GoodsSpecificationImages();
                    g.setGoodId(goodId);
                    g.setSpecificationDetailId(Long.parseLong(s));
                    g.setImagePath(uploadQN(imagePath));
                    imgList.add(g);
                }
            }
        }
        return imgList;
    }

    @Override
    public void updateByPrimaryKeySelective(ReceiveGoodsCache receiveGood) {
        receiveGoodsCacheMapper.updateByPrimaryKeySelective(receiveGood);
    }
    /**
     * @Description: 同步贡云传过来的商品到WMS
     * @Author: zhangrenjie
     * @Date: 2018/2/1 18:01
     *
     */
    @Override
    public ResponseEntity<?> sysProductToWMS() {
        //获取贡云推送过来的商品信息（根据库存表中店铺ID来筛选）
        //获取店铺ID
        BaseRestrictions restrictions = baseRestrictionsService.getBaseRestrictionsForCache(CommonConstants.GYSTOREID);
        String storeId = restrictions.getName();
        //获取接口地址
        BaseRestrictions cache = baseRestrictionsService.getBaseRestrictionsForCache(CommonConstants.SYS_WMS_PRODUCT_URL);
        String url = cache.getName();
        List<Map<String,Object>> resultList  = this.queryAllGYProduct(storeId);
        if (!CollectionUtils.isEmpty(resultList)) {
            for (Map<String, Object> stringObjectMap : resultList) {
                try {
                    Thread.sleep(10);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String json = JSONObject.toJSONString(stringObjectMap);
                String post = "";
                try {
//              post = HttpUtil.doPost(json, url, "application/json");
//                    logger.info("商品："+stringObjectMap.get("productSn")+"开始推送WMS。参数：{"+json+"}");
                    post = HttpUtil.postBody(url, json, ContentType.APPLICATION_JSON);
                    //解析结果
                    Object result = JSONObject.parse(post);
                    JSONObject jsonObject = (JSONObject) result;
                    String code = jsonObject.getString("code");
                    if (code.equals("200")) {//失败记录原因
                        logger.error("规格为:" + stringObjectMap.get("productSn") + "的货品同步WMS失败！原因：" + jsonObject.getString("msg"));
                    } else if(code.equals("100")) {
                        logger.info("规格为:" + stringObjectMap.get("productSn") + "的货品同步WMS成功！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("规格为:"+stringObjectMap.get("productSn")+"的货品同步WMS失败！原因："+e.getMessage());
                }
            }
        }
       /* Map product = new HashedMap<>();
        product.put("productSn", 123456789);
        product.put("barCode", 9999988999L);
        product.put("productName", "测试商品");
        product.put("channelStoreId", 99);
        Object json = JSONObject.toJSON(product);
        System.out.println(json.toString());
        String bbs = "http://192.168.50.143:8080/wms-sf/port/in/xiaopuProduct/addNew";//本地测试
//		String bbs = "http://s.skin79.com.cn/wms-sf/port/in/xiaopuProduct/addNew";//生产
        System.out.println("开始推送。。。。。。。。。。");
//        String post = HttpUtil.postBody(bbs, json.toString(), ContentType.APPLICATION_JSON);
        String post = "";
        try {
             post = HttpUtil.doPost(json.toString(), bbs, "application/json");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("规格为:");
        }
        System.out.println(post);*/
        return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
    }

    private List<Map<String,Object>> queryAllGYProduct(String storeId) {
       return  receiveGoodsCacheMapper.queryAllGYProductByStoreId(storeId);
    }

    /**
     * @Description: 根据商品Id和规格编码查询规格ID并且转换为库存对象
     * @Author: zhangrenjie
     * @Date: 2018/2/1 12:10
     *
     */
    private Inventory changeInVentry(GYInventory i, long goodId, String productId) {
        Inventory inventory = new Inventory();
//        //查询规格
//        productBn = productBn==null?"": productBn.replaceAll("-","");
//        Product pro = productMapper.selectProductByGoodIdAndProductBn(goodId,productBn);
////        if (null == pro) { return null;}
//        if (null == pro ) {
//            logger.error("商品规格："+productBn+"信息不存在");
//            throw new RuntimeException("商品规格："+productBn+"信息不存在");
//        }
        //根据外部编码对应关系查询规格
        if (!String.valueOf(i.getProductId()).equals(productId)) {
            logger.error("外部规格编码："+productId+"不等于库存信息中的规格编码"+i.getProductId());
            throw new RuntimeException("外部规格编码："+productId+"不等于库存信息中的规格编码"+i.getProductId());
        }
        Product pro = productMapper.selectProductByGoodIdAndExtendCode(goodId,i.getProductId());
//        if (null == pro) { return null;}
        if (null == pro ) {
            logger.error("外部规格编码为："+i.getProductId()+"的商品规格信息不存在");
            throw new RuntimeException("外部规格编码为："+i.getProductId()+"的商品规格信息不存在");
        }
        //获取贡云店铺storeId
        BaseRestrictions restrictions = baseRestrictionsService.getBaseRestrictionsForCache(CommonConstants.GYSTOREID);
        String storeId = restrictions.getName();
        inventory.setGoodId(goodId);
        inventory.setProductId(pro.getId());
        inventory.setStoreId(Integer.parseInt(storeId));
//        inventory.setInventoryNum(i.getInventoryNum());
        inventory.setInventoryNum(0);//默认为0
        inventory.setLockInventoryNum(0);
        inventory.setSalePrice(i.getSalePrice());
        inventory.setSettlementPrice(i.getSettlementPrice());
        inventory.setStatus(1);
        inventory.setSettlementRateDealer(100);
        inventory.setSettlementRateManager(0);
        inventory.setXzSalePrice(i.getSalePrice());//和售价保持一致
        return inventory;
    }

    /**
     * @Description: 贡云商品规格转换
     * @Author: zhangrenjie
     * @Date: 2018/2/1 11:42
     *
     */
    private Product changeProduct(ProductSendVo p, long goodId) {
        String nowTime = DateUtils.getNowString(DateUtils.DATE_TIME_FORMAT);
        Product product = new Product();
        product.setGoodId(goodId);
        product.setCreateTime(nowTime);
        //生成唯一规格编码(使用goodid+productId)
        String productBn = String.valueOf(goodId) + String.valueOf(p.getId()) ;
//        product.setProductBn(p.getProductBn()==null?"":p.getProductBn().replaceAll("-",""));
        product.setProductBn(productBn);
        product.setStatus(1);
        product.setSpecName(p.getSpecName());

//        product.setSpecDesc(p.getSpecDesc());
//        String specInfo = p.getSpecInfo();
//        String specInfoNew = "";
//        if (null != specInfo) {
//            String[] split = specInfo.split(",");
//            for (String s : split) {
//                specInfoNew += s +"|";
//            }
//            product.setSpecInfo(specInfoNew.substring(0,specInfoNew.length()-1));
//        }


        //处理规格分类和分类详情(解析json字符串来匹配)
       /* List<SpecDescDetail> specDescDetail = null;
        String specInfoNew = "";
        try {
            specDescDetail = JSON.parseObject(p.getSpecDesc(),new TypeReference<List<SpecDescDetail>>(){});
        } catch (Exception e ) {
            logger.error("JSON解析异常参数：product:"+productBn+"SpecDesc ："+p.getSpecDesc());
            throw new RuntimeException("JSON解析异常参数：product:"+productBn+"SpecDesc ："+p.getSpecDesc());
        }
        if (!CollectionUtils.isEmpty(specDescDetail)) {
            for (SpecDescDetail d : specDescDetail) {
                //处理规格分类详情
                String specificationDetailId = getSpecificationDetailId(null, d.getDetailName());
                if (!StringUtils.isEmpty(specificationDetailId)) {
                    d.setSpecificationDetailId(specificationDetailId);
                    specInfoNew += specificationDetailId +"|";
                }
            }
        }
        String s = "";
        if (specDescDetail != null) {
            s = JSONObject.toJSONString(specDescDetail);
        }
        product.setSpecDesc(s);
        product.setSpecInfo(specInfoNew.substring(0,specInfoNew.length()-1));*/
        //获取商品中的规格ID-保证product中两者一致
        Goods good = goodsMapper.selectGoodsByIdForAll(goodId);
        LinkedList<SpecDescVo> specDescVoList = null;
        Map<String, Object> smap = new HashMap<>();//goods里边的总规格信息
        try {
            specDescVoList = JSON.parseObject(good.getSpecDesc(),new TypeReference<LinkedList<SpecDescVo>>(){});
        } catch (Exception e ) {
            logger.error("JSON解析异常参数：SpecDesc ："+good.getSpecDesc());
        }
        if (!CollectionUtils.isEmpty(specDescVoList)) {
            for (SpecDescVo s : specDescVoList) {
                smap.put(s.getName(),s.getSpecificationId());
                List<SpecDescVoValue> value = s.getValue();
                if (value != null) {
                    for (SpecDescVoValue v : value) {
                        smap.put(v.getDetailName(), v.getSpecificationDetailId());
                    }
                }

            }
        }
        //处理规格分类和分类详情(先根据SpecName根据空格切割来匹配)
        List<SpecDescDetail> specDescDetail = null;
        String specInfoNew = "";
        String[] split = p.getSpecName().split(" ");
        if (split.length>0) {
            specDescDetail = new ArrayList<>();
            for (String s : split) {
                //直接从Goods中获取，保证统一性
                Object detailId = smap.get(s);
                if (detailId == null) {
                    detailId = getSpecificationDetailId(smap.get(s)==null?null:smap.get(s).toString(), s);
                }
                if (detailId!= null) {
                    SpecDescDetail spec = new SpecDescDetail();
                    spec.setSpecificationDetailId(detailId.toString());
                    spec.setDetailName(s);
                    specDescDetail.add(spec);
                    specInfoNew += detailId +"|";
                }
                //根据名字来获取分类详情id
                /* String detailId = getSpecificationDetailId(null, s);
                if (!StringUtils.isEmpty(detailId)) {
                    SpecDescDetail spec = new SpecDescDetail();
                    spec.setSpecificationDetailId(detailId);
                    spec.setDetailName(s);
                    specDescDetail.add(spec);
                    specInfoNew += detailId +"|";
                }*/
            }
        }
        String str = "";
        if (!CollectionUtils.isEmpty(specDescDetail)) {
            str = JSONObject.toJSONString(specDescDetail);
        }
        product.setSpecDesc(str);
        if (!specInfoNew.equals("")) {
            product.setSpecInfo(specInfoNew.substring(0,specInfoNew.length()-1));
        }

        //处理条形码-自己生成
//        try {
//            Thread.sleep(50);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        String barCode = (String.valueOf(System.currentTimeMillis()).substring(6)+p.getId()+specInfoNew).replaceAll("\\|","");
//        if (barCode.length()>20) {//最大20
//            barCode = barCode.substring(0, 20);
//        }
//        product.setBarCode(barCode);
        product.setExtendCode(String.valueOf(p.getId()));//记录对应关系
        return  product;
    }

    /**
     * @Description: 贡云商品信息转换为GoodsNew
     * @Author: zhangrenjie
     * @Date: 2018/1/31 22:19
     *
     */
    private GoodsNew changeGoods(GoodsSendVo g) {
        GoodsNew goods = new GoodsNew();
        goods.setBn(g.getGoodsCode());//商品编码
//        goods.setBrandId(g.getBrandId());//品牌
        goods.setBrandId(250);//默认为其他品牌
        goods.setName(g.getName());
        String title = g.getName();
        if (g.getName().length()>50) {
            title = title.substring(0, 50);
        }
        goods.setTitle(title);
        goods.setLabelName(g.getLabelName());
        goods.setSuggestedPrice(g.getSuggestedPrice());
        goods.setLowestPrice(0);//最低售价
        goods.setUnit(g.getUnit());
        goods.setCategoryParentId(g.getCategoryParentId());//分类 TODO
        goods.setCategoryId(g.getCategoryId());
        goods.setOnlineTime(new Date());
        goods.setOfflineTime(new Date());//默认下架状态
        goods.setTalentLimit(0);//佣金比例
        goods.setThreshold(0);//阈值
        goods.setAscription(new Byte(String.valueOf(g.getAscription())));
        goods.setTalentDisplay(false);//当（ascription为1必选）达人app显示 1是 0 否'
        goods.setDiscount(100);//折扣
        goods.setOperateCosting(0);//运营成本
        goods.setScoreRate(0);//妆币
        goods.setGoodsChannelId(1);
//        goods.setSpecDesc(g.getSpecDesc());
        //处理图片信息
        List<SpecDescVo> specDescVoList = null;
        List<SpecDescVo> specDescVoListNew = null;
        try {
            specDescVoList = JSON.parseObject(g.getSpecDesc(),new TypeReference<List<SpecDescVo>>(){});
        } catch (Exception e ) {
            logger.error("JSON解析异常参数：SpecDesc ："+g.getSpecDesc());
            throw new RuntimeException("JSON解析异常参数：SpecDesc ："+g.getSpecDesc());
        }
        if (!CollectionUtils.isEmpty(specDescVoList)) {
            for (SpecDescVo specDescVo : specDescVoList) {
                //处理规格分类-现根据规格名查询是否存在该规格分类，没有就新增规格分类
                String SpecificationId = getSpecificationId(specDescVo.getName());
                if (!StringUtils.isEmpty(SpecificationId)) {
                    specDescVo.setSpecificationId(SpecificationId);
                }
                List<SpecDescVoValue> values = specDescVo.getValue();
                if (!CollectionUtils.isEmpty(values)) {
                    for (SpecDescVoValue value : values) {
                        //处理规格分类详情
                        String SpecificationDetailId = null;
                        if (!StringUtils.isEmpty(SpecificationId)) {
                            SpecificationDetailId = getSpecificationDetailId(SpecificationId, value.getDetailName());
                        }
                        if (!StringUtils.isEmpty(SpecificationDetailId)) {
                            value.setSpecificationDetailId(SpecificationDetailId);
                        }
                        //处理七牛图片
                        value.setSpecificationDetailImage(uploadQN(value.getSpecificationDetailImage()));
                    }
                }
                specDescVo.setValue(values);
            }
        }
        specDescVoListNew = specDescVoList;
        String s = "";
        if (specDescVoListNew != null) {
            s = JSONObject.toJSONString(specDescVoListNew);
        }
        goods.setSpecDesc(s);
        goods.setServiceDesc(g.getServiceDesc());
        goods.setRemark(g.getRemark());
        goods.setCreateTime(new Date());
        goods.setWxSmallImgpath(uploadQN(g.getWxSmallImgpath()));
        goods.setGoodsWidthPic(null);
        goods.setGoodsType(true);//默认B区
        goods.setSelfSupport(true);//默认非自营
        goods.setSalesType(true);//正常商品
        goods.setCanShoppingcart(true);//加购物车
        goods.setSalesType(false);//默认0（正常）
        return goods;
    }
    /**
     * @Description: 修复异常数据——只更新规格参数SpecDesc
     * @Author: zhangrenjie
     * @Date: 2018/3/5 9:46
     *
     */
    private GoodsNew changeGoodsNew(GoodsSendVo g) {
        GoodsNew goods = new GoodsNew();
        //处理图片信息
        List<SpecDescVo> specDescVoList = null;
        List<SpecDescVo> specDescVoListNew = null;
        try {
            specDescVoList = JSON.parseObject(g.getSpecDesc(),new TypeReference<List<SpecDescVo>>(){});
        } catch (Exception e ) {
            logger.error("JSON解析异常参数：SpecDesc ："+g.getSpecDesc());
            throw new RuntimeException("JSON解析异常参数：SpecDesc ："+g.getSpecDesc());
        }
        if (!CollectionUtils.isEmpty(specDescVoList)) {
            for (SpecDescVo specDescVo : specDescVoList) {
                //处理规格分类-现根据规格名查询是否存在该规格分类，没有就新增规格分类
                String SpecificationId = getSpecificationId(specDescVo.getName());
                if (!StringUtils.isEmpty(SpecificationId)) {
                    specDescVo.setSpecificationId(SpecificationId);
                }
                List<SpecDescVoValue> values = specDescVo.getValue();
                if (!CollectionUtils.isEmpty(values)) {
                    for (SpecDescVoValue value : values) {
                        //处理规格分类详情
                        String SpecificationDetailId = null;
                        if (!StringUtils.isEmpty(SpecificationId)) {
                            SpecificationDetailId = getSpecificationDetailId(SpecificationId, value.getDetailName());
                        }
                        if (!StringUtils.isEmpty(SpecificationDetailId)) {
                            value.setSpecificationDetailId(SpecificationDetailId);
                        }
                        //处理七牛图片
                        value.setSpecificationDetailImage(uploadQN(value.getSpecificationDetailImage()));
                    }
                }
                specDescVo.setValue(values);
            }
        }
        specDescVoListNew = specDescVoList;
        String s = "";
        if (specDescVoListNew != null) {
            s = JSONObject.toJSONString(specDescVoListNew);
        }
        goods.setSpecDesc(s);
        return goods;
    }
    /**
     * @Description: 获取商品规格分类详情主键ID
     * @Author: zhangrenjie
     * @Date: 2018/2/28 15:27
     *
     */
    private String getSpecificationDetailId(String specificationId,String detailName) {
        String detailId = null;
        if (StringUtils.isEmpty(detailName)) {
            return detailId;
        }
        SpecificationDetail detail = new SpecificationDetail();
        detail.setDetailName(detailName);
        if (!StringUtils.isEmpty(specificationId)) {
            detail.setSpecificationId(Integer.valueOf(specificationId));
        }
        List<SpecificationDetail> selectAll = specificationDetailMapper.selectAll(detail);
        if (!CollectionUtils.isEmpty(selectAll)) {
            detailId = String.valueOf(selectAll.get(0).getId());
        } else {
            detail.setOrderNo(1);
            int add = specificationDetailMapper.insertSelective(detail);
            if (add < 1) {
                throw new RuntimeException("新增规格分类详情失败：detailName ："+detailName+"||specificationId:"+specificationId);
            }
            detailId = String.valueOf(specificationDetailMapper.selectAll(detail).get(0).getId());
        }
        return detailId;
    }

    /**
     * @Description: 获取商品规格分类主键ID
     * @Author: zhangrenjie
     * @Date: 2018/2/28 15:15
     *
     */
    private String getSpecificationId(String name) {
        String id = null;
        if (StringUtils.isEmpty(name)) {
            return id;
        }
        Specification s = new Specification();
        s.setName(name);
        List<Specification> selectAll = specificationMapper.selectAll(s);
        if (!CollectionUtils.isEmpty(selectAll)) {
            Specification specification = selectAll.get(0);
            id = String.valueOf(specification.getId());
        } else {
            s.setOrderNo(1);
            int add = specificationMapper.insertSelective(s);
            if (add<1) {
                throw new RuntimeException("新增规格分类失败：name ："+name);
            }
            List<Specification> list = specificationMapper.selectAll(s);
            Specification specification = list.get(0);
            id = String.valueOf(specification.getId());
        }
        return id;
    }

    /**
     * @Description: 图片上传七牛返回新url地址
     * @Author: zhangrenjie
     * @Date: 2018/2/5 9:46
     *
     */

    private String uploadQN(String  imgUrl){
        if (StringUtils.isEmpty(imgUrl)) {
            return "";
        }
        if (!imgUrl.startsWith("http")) {//追加吉贡图片域名
            imgUrl = "http://img.jioao.cn/" + imgUrl;
        }
//        imgUrl = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3217485332,2997675122&fm=27&gp=0.jpg";
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
//        BufferedOutputStream bos = null;
        byte[] buf = null;
        try {
            URL url = null;
//            buf = new byte[1024];
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
//            File file = new File("d:/test/myFile.jpg");
//            FileOutputStream fileOutputStream = new FileOutputStream(file);
//            bos = new BufferedOutputStream(fileOutputStream);
//            while (true) {
//                int read = bis.read(buf, 0, buf.length);
//                if (read == -1) {
//                    break;
//                }
//                bos.write(buf, 0, read);
//            }
            buf = toByteArray(bis);
//            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bis.close();
                httpUrl.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String s = imgUrl.substring(imgUrl.length() - 3);//图片后缀名
        String jpgUrl = "";
        if (buf != null) {
            jpgUrl = QiniuUtils.uploadByBytys64("images/gongyun/", buf, s);
        }
        return jpgUrl;
    }
    /**
     * @Description: 从输入流获取数据转换为byte数组
     * @Author: zhangrenjie
     * @Date: 2018/2/5 11:35
     *
     */
    private  byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
    @Override
    @Transactional
    public void updateProductData(List<ReceiveGoodsCache> cacheList) {
        /*for (ReceiveGoodsCache receiveGoodsCache : cacheList) {
            LinkedList<SpecDescVo> specDescVoList = null;
            List<String> ids = null;
            List<Goods> goods = goodsMapper.selectGoodsByBN(receiveGoodsCache.getGoodsCode());
            if (!CollectionUtils.isEmpty(goods)) {
                Goods g = goods.get(0);
                //获取规格
                try {
                    specDescVoList = JSON.parseObject(g.getSpecDesc(),new TypeReference<LinkedList<SpecDescVo>>(){});
                } catch (Exception e ) {
                    logger.error("JSON解析异常参数：SpecDesc ："+g.getSpecDesc());
                }
                if (specDescVoList != null) {
                    List<SpecDescVoValue> value = specDescVoList.get(0).getValue();
                    if (value != null) {
//                            for (SpecDescVoValue v : value) {
//
//                                ids.add(v.getSpecificationDetailId());
//                            }
                        ids.add(value.get(0).getSpecificationDetailId());
                    }
                }
                //获取商品的所有货品
                List<Product> products = productMapper.selectProductByGoodId(g.getId());
                if (!CollectionUtils.isEmpty(products)) {
                    for (Product product : products) {
                        //只更新字段SpecInfo
                        String specInfo = product.getSpecInfo();
                        specInfo = specInfo.substring(specInfo.indexOf("|"),specInfo.length());
                        product.setSpecInfo(ids.get(0)+"|"+specInfo);
                        productMapper.updateByPrimaryKeySelective(product);
                    }
                }
            }
        }*/
        //查询所有吉贡的货品
        BaseRestrictions restrictions = baseRestrictionsService.getBaseRestrictionsForCache(CommonConstants.GYSTOREID);
        String storeId = restrictions.getName();
        List<Map<String, Object>> allGYProduct = this.queryAllGYProduct("46");//吉贡的商品
        for (Map<String, Object> objectMap : allGYProduct) {
            //商品ID
            Object goodId = objectMap.get("goodId");
//            if (Long.valueOf(goodId.toString()) != 4251) {
//                continue;
//            }
            Goods good = goodsMapper.selectGoodsByIdForAll(Long.valueOf(goodId.toString()));
            LinkedList<SpecDescVo> specDescVoList = null;
            Map<String, Object> smap = new HashMap<>();//goods里边的总规格信息
            try {
                specDescVoList = JSON.parseObject(good.getSpecDesc(),new TypeReference<LinkedList<SpecDescVo>>(){});
            } catch (Exception e ) {
                logger.error("JSON解析异常参数：SpecDesc ："+good.getSpecDesc());
            }
            if (!CollectionUtils.isEmpty(specDescVoList)) {
                for (SpecDescVo s : specDescVoList) {
                    smap.put(s.getName(),s.getSpecificationId());
                    List<SpecDescVoValue> value = s.getValue();
                    if (value != null) {
                        for (SpecDescVoValue v : value) {
                            smap.put(v.getDetailName(), v.getSpecificationDetailId());
                        }
                    }

                }
            }
            //处理规格分类和分类详情(先根据SpecName根据空格切割来匹配)
            List<SpecDescDetail> specDescDetail = null;
            String specInfoNew = "";
            //查询product
            Product p = productMapper.selectProductByGoodIdAndExtendCode(Long.valueOf(goodId.toString()), Long.valueOf(objectMap.get("yundaProductSn").toString()));

            String[] split = p.getSpecName().split(" ");
            if (split.length>0) {
                specDescDetail = new ArrayList<>();
                for (String s : split) {
                    //直接从Goods中获取，保证统一性
                    Object detailId = smap.get(s);
                    if (detailId!= null) {
                        SpecDescDetail spec = new SpecDescDetail();
                        spec.setSpecificationDetailId(detailId.toString());
                        spec.setDetailName(s);
                        specDescDetail.add(spec);
                        specInfoNew += detailId +"|";
                    }

                }
            }
            p.setSpecInfo(specInfoNew);
            String str = "";
            if (!CollectionUtils.isEmpty(specDescDetail)) {
                str = JSONObject.toJSONString(specDescDetail);
            }
            p.setSpecDesc(str);
            if (!specInfoNew.equals("")) {
                p.setSpecInfo(specInfoNew.substring(0,specInfoNew.length()-1));
            }
            //更新product
            productMapper.updateByPrimaryKeySelective(p);
        }
    }



}
